package com.comac.tasks.manager.app.mq.listener;

import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.Message;
import com.comac.mom.simpleintegration.mq.BaseMessageListener;
import com.comac.tasks.manager.app.domain.gateway.TasksManagerGateway;
import com.comac.tasks.manager.app.dto.TasksManagerUpDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;

/**
 * 注解指定订阅的主题
 *
 * @author wfb
 */
@Component(value = "TASKS-MANAGER-UPDATE")
@Slf4j
public class TasksManagerUpdateListener extends BaseMessageListener {

    @Autowired
    private TasksManagerGateway tasksManagerGateway;

    @Override
    public Action consume(Message message) {
        byte[] body = message.getBody();
        String msg = new String(body);
        log.info("Receive body {} from {}", msg, message.getTopic());
        TasksManagerUpDTO tasksManagerUpDTO = null;
        try {
            tasksManagerUpDTO = deserialize(message, TasksManagerUpDTO.class);
            log.info("tasksManagerUpDTO = {}", tasksManagerUpDTO);
            if (null == tasksManagerUpDTO) {
                log.warn("TasksManagerUpdateListener,deserialize tasksManagerUpDTO is null,ReconsumeLater");
                throw new BizException("TasksManagerUpdateListener,deserialize tasksManagerUpDTO is null,ReconsumeLater,tasksManagerUpDTO：" + tasksManagerUpDTO);
            }
            log.info("TasksManagerUpdateListener,tasksManagerUpDTO:{}", JSONObject.toJSONString(tasksManagerUpDTO));
            if (CollectionUtils.isEmpty(tasksManagerUpDTO.getTaskInstanceIds()) &&
                    CollectionUtils.isEmpty(tasksManagerUpDTO.getProcessInstanceIds())) {
                log.warn("TasksManagerUpdateListener,流程实例id为空，不能进行消费消息");
                throw new BizException("TasksManagerUpdateListener,流程实例id为空，不能进行消费消息");
            }
            tasksManagerGateway.updateStatus(tasksManagerUpDTO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("mq消费消息失败");
            log.error("mqConsume error msg:" + e.toString());
            log.error("mqConsume stackTrace:" + Arrays.toString(e.getStackTrace()));
            throw new BizException("更新代办消息消费失败：" + e.getMessage());
        }
        return Action.CommitMessage;
    }
}
